//! 重构后的Cluster模式Redis服务器实现
//! 
//! 基于SOLID原则重构，实现：
//! 1. 单一职责：专注于Cluster模式的服务器管理
//! 2. 依赖倒置：依赖抽象接口而非具体实现
//! 3. 开闭原则：支持扩展而无需修改现有代码

use crate::server::enhanced_traits::*;
// use crate::server::traits::ServerMode; // 未使用的导入
use crate::server::config_manager::{ConfigSource};
use crate::server::service_manager::ServiceManager;
use crate::server::component_factory::DefaultComponentFactory;
use crate::server::event_publisher::create_production_event_publisher;
use crate::storage::RedisServerMode;
use async_trait::async_trait;
use std::io;
use std::sync::Arc;
use tracing::{info, warn};

/// 重构后的Cluster服务器
/// 
/// 职责单一：管理Cluster模式的Redis服务器
/// 依赖抽象：通过trait接口与其他组件交互
pub struct RefactoredClusterServer {
    /// 服务配置
    config: Box<dyn ServerConfig>,
    
    /// 服务管理器
    service_manager: Option<ServiceManager>,
    
    /// 组件工厂
    component_factory: Arc<dyn ServiceComponentFactory>,
    
    /// 事件发布器
    event_publisher: Arc<dyn ServerEventPublisher>,
    
    /// 服务器状态
    is_running: bool,
}

impl RefactoredClusterServer {
    /// 从配置文件创建新的Cluster服务器（自动检测格式）
    pub async fn new(config_path: &str) -> io::Result<Self> {
        use crate::server::config_manager::{FileConfigSource, ConfigFormat};
        
        let config_source = FileConfigSource::new(config_path.to_string(), ConfigFormat::Auto);
        let config = config_source.load_config().await
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
        
        Self::from_config(config, None).await
    }
    
    /// 从TOML配置文件创建新的Cluster服务器
    pub async fn from_toml(config_path: &str) -> io::Result<Self> {
        use crate::server::config_manager::{FileConfigSource, ConfigFormat};
        
        let config_source = FileConfigSource::new(config_path.to_string(), ConfigFormat::Toml);
        let config = config_source.load_config().await
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
        
        Self::from_config(config, None).await
    }
    
    /// 使用自定义工厂创建Cluster服务器
    pub async fn with_factory(
        config: Box<dyn ServerConfig>,
        component_factory: Arc<dyn ServiceComponentFactory>,
    ) -> io::Result<Self> {
        Self::from_config(config, Some(component_factory)).await
    }
    
    /// 从配置创建Cluster服务器
    pub async fn from_config(
        config: Box<dyn ServerConfig>,
        component_factory: Option<Arc<dyn ServiceComponentFactory>>,
    ) -> io::Result<Self> {
        // 验证配置模式
        if config.mode() != RedisServerMode::Cluster {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("配置模式不匹配，期望Cluster，实际: {:?}", config.mode())
            ));
        }
        
        // 验证配置
        config.validate().map_err(|e| {
            io::Error::new(io::ErrorKind::InvalidInput, format!("配置验证失败: {}", e))
        })?;
        
        let component_factory = component_factory.unwrap_or_else(|| Arc::new(DefaultComponentFactory));
        let event_publisher = Arc::new(create_production_event_publisher().await);
        
        // 获取集群配置详情
        let cluster_config = config.extra_config()
            .and_then(|extra| extra.downcast_ref::<crate::cluster::ClusterConfig>())
            .ok_or_else(|| io::Error::new(
                io::ErrorKind::InvalidInput,
                "缺少集群配置信息"
            ))?;
        
        info!("🏗️ 创建Cluster服务器");
        info!("🎯 节点ID: {}", cluster_config.node_id);
        info!("📍 Redis端口: {}", cluster_config.redis_port);
        info!("📍 集群端口: {}", cluster_config.cluster_port);
        
        Ok(Self {
            config,
            service_manager: None,
            component_factory,
            event_publisher,
            is_running: false,
        })
    }
    
    /// 从已有集群配置创建服务器
    pub async fn from_cluster_config(cluster_config: crate::cluster::ClusterConfig) -> io::Result<Self> {
        let bind_address = cluster_config.redis_addr();
        let server_config = Box::new(ClusterConfig {
            bind_address,
            cluster_config,
        });
        
        Self::from_config(server_config, None).await
    }
    
    /// 获取服务配置
    pub fn config(&self) -> &dyn ServerConfig {
        self.config.as_ref()
    }
    
    /// 获取集群配置
    pub fn cluster_config(&self) -> Option<&crate::cluster::ClusterConfig> {
        self.config.extra_config()
            .and_then(|extra| extra.downcast_ref::<crate::cluster::ClusterConfig>())
    }
    
    /// 获取事件发布器
    pub fn event_publisher(&self) -> Arc<dyn ServerEventPublisher> {
        Arc::clone(&self.event_publisher)
    }
    
    /// 获取绑定地址
    pub fn bind_address(&self) -> &str {
        self.config.bind_address()
    }
}

#[async_trait]
impl EnhancedServerMode for RefactoredClusterServer {
    fn config(&self) -> &dyn ServerConfig {
        self.config.as_ref()
    }
    
    fn component_factory(&self) -> &dyn ServiceComponentFactory {
        self.component_factory.as_ref()
    }
    
    fn event_publisher(&self) -> &dyn ServerEventPublisher {
        self.event_publisher.as_ref()
    }
    
    /// 具体的启动实现
    async fn do_start(&mut self) -> io::Result<()> {
        if self.is_running {
            warn!("Cluster服务器已经在运行中");
            return Ok(());
        }
        
        info!("🚀 启动Cluster服务器");
        
        if let Some(cluster_config) = self.cluster_config() {
            info!("🎯 节点ID: {}", cluster_config.node_id);
            info!("📍 Redis端口: {}", cluster_config.redis_port);
            info!("📍 集群端口: {}", cluster_config.cluster_port);
        }
        
        // 创建服务管理器
        let mut service_manager = ServiceManager::new(
            self.config.clone_config(),
            Arc::clone(&self.event_publisher),
        );
        
        // 创建集群服务组件（优先启动）
        info!("🔗 步骤 1/2: 创建集群服务组件");
        if let Ok(Some(cluster_service)) = self.component_factory
            .create_cluster_service(self.config.as_ref())
            .await {
            service_manager.add_service(cluster_service);
        } else {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                "创建集群服务组件失败"
            ));
        }
        
        // 创建Redis服务组件
        info!("🔗 步骤 2/2: 创建Redis服务组件（集群模式）");
        let redis_service = self.component_factory
            .create_redis_service(self.config.as_ref())
            .await?;
        service_manager.add_service(redis_service);
        
        // 创建监控服务组件（可选）
        if let Ok(Some(monitoring_service)) = self.component_factory
            .create_monitoring_service(self.config.as_ref())
            .await {
            info!("🔧 创建监控服务组件");
            service_manager.add_service(monitoring_service);
        }
        
        // 启动所有服务
        service_manager.start().await?;
        
        self.service_manager = Some(service_manager);
        self.is_running = true;
        
        info!("✅ Cluster服务器启动成功");
        
        if let Some(cluster_config) = self.cluster_config() {
            info!("💡 Redis客户端连接: redis://127.0.0.1:{}", cluster_config.redis_port);
            info!("💡 集群通信端口: {}", cluster_config.cluster_port);
        }
        
        Ok(())
    }
    
    /// 具体的停止实现
    async fn do_stop(&mut self) -> io::Result<()> {
        if !self.is_running {
            warn!("Cluster服务器未在运行中");
            return Ok(());
        }
        
        info!("🛑 停止Cluster服务器");
        
        if let Some(mut service_manager) = self.service_manager.take() {
            service_manager.stop().await?;
        }
        
        self.is_running = false;
        info!("✅ Cluster服务器已停止");
        Ok(())
    }
    
    fn is_running(&self) -> bool {
        self.is_running
    }
}

#[async_trait]
impl ServiceLifecycle for RefactoredClusterServer {
    fn service_name(&self) -> &'static str {
        "RefactoredClusterServer"
    }
    
    async fn start(&mut self) -> io::Result<()> {
        // 使用EnhancedServerMode的模板方法
        <Self as EnhancedServerMode>::start(self).await
    }
    
    async fn stop(&mut self) -> io::Result<()> {
        // 使用EnhancedServerMode的模板方法
        <Self as EnhancedServerMode>::stop(self).await
    }
    
    fn is_running(&self) -> bool {
        self.is_running
    }
    
    async fn graceful_shutdown(&mut self, timeout_secs: u64) -> io::Result<()> {
        if !self.is_running {
            return Ok(());
        }
        
        info!("🔄 Cluster服务器开始优雅关闭（超时: {}秒）", timeout_secs);
        
        if let Some(service_manager) = &mut self.service_manager {
            service_manager.graceful_shutdown(timeout_secs).await?;
        }
        
        self.is_running = false;
        info!("✅ Cluster服务器优雅关闭完成");
        Ok(())
    }
}

#[async_trait]
impl HealthCheck for RefactoredClusterServer {
    async fn health_check(&self) -> Result<HealthStatus, String> {
        if !self.is_running {
            return Ok(HealthStatus::Unhealthy("服务器未运行".to_string()));
        }
        
        // 检查服务管理器的健康状态
        if let Some(service_manager) = &self.service_manager {
            let base_health = service_manager.health_check().await?;
            
            // 对于集群服务器，额外检查集群特定的健康状态
            match base_health {
                HealthStatus::Healthy => {
                    // TODO: 添加集群特定的健康检查
                    // 例如：检查节点连接状态、槽位分配等
                    Ok(HealthStatus::Healthy)
                }
                other => Ok(other),
            }
        } else {
            Ok(HealthStatus::Unhealthy("服务管理器未初始化".to_string()))
        }
    }
    
    async fn diagnostics(&self) -> Vec<DiagnosticInfo> {
        let mut diagnostics = Vec::new();
        
        // 服务器自身的诊断信息
        let cluster_info = if let Some(cluster_config) = self.cluster_config() {
            format!("节点ID: {}, Redis端口: {}, 集群端口: {}", 
                   cluster_config.node_id, 
                   cluster_config.redis_port, 
                   cluster_config.cluster_port)
        } else {
            "集群配置不可用".to_string()
        };
        
        diagnostics.push(DiagnosticInfo {
            component: "RefactoredClusterServer".to_string(),
            status: if self.is_running { "Running" } else { "Stopped" }.to_string(),
            details: Some(cluster_info),
        });
        
        // 服务管理器的诊断信息
        if let Some(service_manager) = &self.service_manager {
            let mut manager_diagnostics = service_manager.diagnostics().await;
            diagnostics.append(&mut manager_diagnostics);
        }
        
        diagnostics
    }
}

// =============================================================================
// 兼容性适配器 - 保持现有API
// =============================================================================

/// 兼容性适配器 - 将新实现适配到旧的ServerMode trait
pub struct ClusterServerAdapter {
    inner: RefactoredClusterServer,
}

impl ClusterServerAdapter {
    /// 创建适配器
    pub async fn new(config_path: &str) -> io::Result<Self> {
        let inner = RefactoredClusterServer::new(config_path).await?;
        Ok(Self { inner })
    }
    
    /// 从TOML配置文件创建适配器
    pub async fn from_toml(config_path: &str) -> io::Result<Self> {
        let inner = RefactoredClusterServer::from_toml(config_path).await?;
        Ok(Self { inner })
    }
    
    /// 从配置创建适配器
    pub async fn from_config(config: crate::cluster::ClusterConfig) -> io::Result<Self> {
        let inner = RefactoredClusterServer::from_cluster_config(config).await?;
        Ok(Self { inner })
    }
    
    /// 从重构后的服务器创建适配器
    pub fn from_refactored(server: RefactoredClusterServer) -> Self {
        Self { inner: server }
    }
    
    /// 获取内部的重构后服务器
    pub fn into_refactored(self) -> RefactoredClusterServer {
        self.inner
    }
    
    /// 获取内部服务器的引用
    pub fn refactored(&self) -> &RefactoredClusterServer {
        &self.inner
    }
    
    /// 获取内部服务器的可变引用
    pub fn refactored_mut(&mut self) -> &mut RefactoredClusterServer {
        &mut self.inner
    }
}

#[async_trait]
impl crate::server::traits::ServerMode for ClusterServerAdapter {
    async fn start(&mut self) -> io::Result<()> {
        EnhancedServerMode::start(&mut self.inner).await
    }
    
    async fn stop(&mut self) -> io::Result<()> {
        EnhancedServerMode::stop(&mut self.inner).await
    }
    
    fn is_running(&self) -> bool {
        EnhancedServerMode::is_running(&self.inner)
    }
    
    fn get_mode(&self) -> crate::storage::RedisServerMode {
        self.inner.config().mode()
    }
}

// =============================================================================
// 便利构造函数
// =============================================================================

/// 创建生产环境的Cluster服务器
pub async fn create_production_cluster_server(config_path: &str) -> io::Result<RefactoredClusterServer> {
    use crate::server::component_factory::ExtendedComponentFactory;
    use crate::server::config_manager::{FileConfigSource, ConfigFormat};
    
    let config_source = FileConfigSource::new(config_path.to_string(), ConfigFormat::Auto);
    let config = config_source.load_config().await
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
    
    RefactoredClusterServer::with_factory(
        config,
        Arc::new(ExtendedComponentFactory::new()),
    ).await
}

/// 创建测试用的Cluster服务器
#[cfg(test)]
pub async fn create_test_cluster_server(config_path: &str) -> io::Result<RefactoredClusterServer> {
    // 测试环境可以使用模拟的组件工厂
    RefactoredClusterServer::new(config_path).await
}

/// 从配置文件创建Cluster服务器
pub async fn create_cluster_server_from_config(
    config_path: &str,
) -> io::Result<RefactoredClusterServer> {
    RefactoredClusterServer::new(config_path).await
}

/// 从集群配置创建Cluster服务器
pub async fn create_cluster_server_from_cluster_config(
    cluster_config: crate::cluster::ClusterConfig,
) -> io::Result<RefactoredClusterServer> {
    RefactoredClusterServer::from_cluster_config(cluster_config).await
}